#include "Game.h"
#include "InputHangdler.h"
#include "SoundManager.h"

#include <iostream>

using namespace std;

Game* Game::s_pInstance = 0;

Game::Game()
{
	m_bAlive = true;
	m_pRenderer = NULL;
	m_pWindow = NULL;
	timeGenarateCreep = 0.0f;
}

bool Game::init(char* title, int xpos, int ypos, int width, int height, Uint32 flags)
{
	srand(time(NULL));
	//try init SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
	{
		cout << "SDL inicialitzat" << endl;
		//init the window
		m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
		if (m_pWindow != 0) // init window
		{
			cout << "SDL window incialitzat" << endl;
			m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
			if (m_pRenderer != 0) //renderer init
			{
				cout << "renderer inicialitzat correctament" << endl;
				SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);
			}
			else{
				cout << "renderer inicialitzacio error" << endl;
				return false;
			}
		}
		else{
			cout << "window inicialitzacio error" << endl;
			return false;
		}
	}
	else{
		cout << "SDL inicialitzacio error" << endl;
		return false;
	}
	cout << "incialitacio correcte " << endl;
	m_running = true;

	SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);

	
	m_pGameStateMachine = new GameStateMachine();
	m_pGameStateMachine->changeState(new MenuState());

	

	return true;
}

void Game::render()
{
	SDL_RenderClear(m_pRenderer); //clean renderer

	m_pGameStateMachine->render();

	SDL_RenderPresent(m_pRenderer); // swap buffer
}

void Game::handleEvents()
{
	
	TheInputHangdler::Instance()->update();
}

void Game::update()
{
	m_pGameStateMachine->update();
}


void Game::clean()
{	
	SDL_DestroyWindow(m_pWindow);
	SDL_DestroyRenderer(m_pRenderer);
	SDL_Quit();
}

bool Game::running() const
{
	return m_running;
}

void Game::quit()
{
	clean();
}

SDL_Renderer* Game::getRenderer() const
{
	return m_pRenderer;
}

GameStateMachine* Game::getStateMachine() const
{
	return m_pGameStateMachine;
}

void Game::getRunning(const int &a)
{
	if (a == 0)
		m_running = false;
	else
		m_running = true;
}